package ${package}.util;

import ${package}.dao.UserDao;
import ${package}.model.entity.Authority;
import ${package}.model.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Set;

/**
 * UserDetailsService implementation.
 */
public class UserDetailServiceImpl implements UserDetailsService {
    /**
     * Autowired UserDao instance.
     */
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(final String username) {

        User user = userDao.getByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + username);
        }

        Set<Authority> authorities = user.getAuthorities();
        Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>(authorities.size());
        for (Authority authority : authorities) {
            grantedAuthorities.add(new GrantedAuthorityImpl(authority.getAuthority()));
        }

        return new UserInfo(user, grantedAuthorities.toArray(new GrantedAuthority[grantedAuthorities.size()]));
    }
}

